
#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    struct timeval tv;

    setbuf(stdout, NULL);

    for (int i = 0; ; i++) {
        tv.tv_sec = 1;
        tv.tv_usec = 0;
        fd_set  rfds;
        FD_ZERO(&rfds);
        FD_SET(STDIN_FILENO, &rfds);
        int ret = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv);
        if (ret > 0) {
            char buffer[1024] = {0};
            int bytes_read = read(STDIN_FILENO, buffer, sizeof(buffer) - 1);
            buffer[bytes_read] = 0;
            printf("Input: %s", buffer);
            if (strncmp(buffer, "quit", 4) == 0)
                break;
        } else if (ret == 0) {
            printf("loop %d times\n", i);
        } else {
            perror("select");
            break;
        }
        // fflush(stdout);
    }
    return 0;
}

